package cn.web.tunnelrobot.websocket;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @description://服务端线程类
 * //继承Thread类的话，必须重写run方法，在run方法中定义需要执行的任务。
 * @author: LiChuang
 * @createDate: 2021-06-30
 * @version: 1.0
 */
public class ServerThread  extends Thread {
    static Logger logger = LoggerFactory.getLogger(ServerThread.class);
    private static Socket socket ;
    static InputStream inputStream;
    static OutputStream outputStream;

    public ServerThread(Socket socket){
        this.socket=socket;
    }

    public static String run(String message) {
        try {
            if(StringUtils.isNotEmpty(message)){
                //向客户端发送消息
                outputStream = socket.getOutputStream();
                outputStream.write(message.getBytes());
            }
            while (true){
                //接收客户端的消息并打印
                inputStream=socket.getInputStream();
                byte[] bytes = new byte[30];
                inputStream.read(bytes);
                message = new String(bytes);
                logger.info("客户端消息"+message);
                return message;
            }
        } catch (Exception e) {
            logger.error("硬件采集数据-客户端主动断开连接了");
        }
        //操作结束，关闭socket
        try{
            socket.close();
        }catch(IOException e){
            logger.error("硬件采集数据-关闭连接出现异常");
        }
        return message;
    }
}
